package com.example.emos.wx.config;

import com.example.emos.wx.shiro.OAuth2Filter;
import com.example.emos.wx.shiro.OAuth2Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
//    @Autowired
//    private OAuth2Realm oAuth2Realm;

    @Bean("securityManager")
    public DefaultWebSecurityManager defaultSecurityManager(OAuth2Realm oAuth2Realm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        // 设置自定义realm
        securityManager.setRealm(oAuth2Realm);
        return securityManager;
    }

    @Bean("shiroFilterFactoryBean")
    public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager defaultWebSecurityManager, OAuth2Filter oAuth2Filter) {
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        filterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        // 设置shiro自定义filter
        HashMap<String, Filter> filtersMap = new HashMap<>();
        filtersMap.put("oauth2", oAuth2Filter);
        filterFactoryBean.setFilters(filtersMap);

        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/swagger-ui/**", "anon");
        filterMap.put("/v3/**", "anon");
        filterMap.put("/swagger-resources/**", "anon");
        filterMap.put("/webjars/**", "anon");
        filterMap.put("/user/register", "anon");
        filterMap.put("/user/login", "anon");
        filterMap.put("/**", "oauth2");
        filterFactoryBean.setFilterChainDefinitionMap(filterMap);
        return filterFactoryBean;
    }

//    @Bean("shiroFilterChain")
//    public DefaultShiroFilterChainDefinition shiroFilterChainDefinition() {
//        DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
//        chainDefinition.addPathDefinition("/user/login", "anno");
//        return chainDefinition;
//    }
}
